<?php
/**
 * Created by PhpStorm.
 * User: tangchao
 * Date: 19-3-27
 * Time: 下午1:26
 */

namespace App\HttpController\Api;


use EasySwoole\Core\Component\Di;
use EasySwoole\Core\Component\Logger;
use EasySwoole\Core\Swoole\Task\TaskManager;

class Video extends Base
{
    /**
     * 视频信息
     * @return bool|void
     */
    public function index()
    {
        $id = intval($this->params['id']);
        if (empty($id)){
            return $this->backError('未获取到参数id');
        }

        //获取基本信息
        try{
            $model = new \App\Model\Video();
            $video = $model->getById($id);
        }catch (\Exception $e){
            Logger::getInstance()->log('video'.json_encode($e->getMessage()));
            return $this->backError('未查询到相关数据');
        }

        if (!$video || $video['status'] != \Yaconf::get('easyswoole.status.normal')){
            return $this->backError('该视频已不存在或被冻结');
        }

        $video['duration'] = $model->videoTimeFormat($video['duration']);
        $video['create_time'] = $model->timeFormat($video['create_time']);
        $this->playNum($id);
        return $this->backSuccess($video);
    }

    /**
     * 记录播放次数
     * @param $id
     */
    public function playNum($id)
    {
        //投放到task异步任务
        TaskManager::async(function () use($id){
            //业务
            $redis = Di::getInstance()->get("REDIS");
            $res = $redis->zincrby(\Yaconf::get('easyswoole.key.videoPlayNum'),1,$id);
            //todo 做持久化
            return !empty($res) ? true : false;
        },function (){});
    }

    /**
     * 排行
     */
    public function rank()
    {
        $res = Di::getInstance()->get("REDIS")->zrevrange(\Yaconf::get('easyswoole.key.videoPlayNum'),0,-1,"withscores");
        $result = [];
        if (!empty($res)){
            foreach ($res as $k => $re) {
                $temp = [
                    'id' =>  $k,
                    'play_num' => $re
                ];
                $result[] = $temp;
            }
        }
        return  $this->backSuccess($result);
    }


}